<template>
  <div class="app-container">
    <!-- 顶部导航 -->
    <div class="top-navbar">
      <el-row type="flex" justify="space-between" align="middle">
        <el-col :span="12">
          <!-- <div class="left-nav">
            <span class="title">仓库</span>
            <el-button type="text" icon="el-icon-setting">仓库管理</el-button>
          </div> -->
          <el-input
            v-model="listQuery.name"
            placeholder="请输入仓库名称"
            clearable
            style="width: 250px"
          />
          <!-- <el-checkbox
              v-model="listQuery.showDisabled"
              style="margin-left: 10px"
              >显示禁用部门</el-checkbox
            > -->
          <el-button
            type="primary"
            style="margin-left: 10px"
            @click="handleFilter"
          >查询</el-button>
        </el-col>
        <el-col :span="12">
          <div class="right-nav">
            <el-button type="success" icon="el-icon-plus" @click="handleAdd">新增</el-button>
            <!-- <el-button @click="handleImport">导入</el-button>
            <el-button @click="handleExport">导出</el-button>
            <el-button @click="handleRefresh">刷新</el-button> -->
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 表格区域 -->
    <el-table
      v-loading="listLoading"
      :data="warehouseList"
      element-loading-text="加载中"
      border
      fit
      highlight-current-row
      header-cell-style="background-color: #f5f7fa; color: #333;"
    >
      <el-table-column label="仓库名称" prop="name" align="center" />
      <el-table-column label="仓管" prop="warehouseUserName" align="center" />

      <!-- <el-table-column label="状态" align="center" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.enabled"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column> -->

      <el-table-column label="操作" width="250" align="center">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">
            <!-- <i class="el-icon-edit"></i> -->
            编辑
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">
            <!-- <i class="el-icon-delete"></i> -->
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->

    <el-row :gutter="10" style="margin-top: 20px" type="flex" justify="end">
      <el-pagination
        background
        :current-page="listQuery.page"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="listQuery.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-row>

    <!-- 新增/编辑仓库对话框 -->
    <el-dialog
      :title="form.id ? '编辑' : '新增'"
      :visible.sync="dialogFormVisible"
      width="500px"
    >
      <el-form
        ref="warehouseForm"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="仓库名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入仓库名称" />
        </el-form-item>

        <el-form-item label="仓库管理员" prop="warehouseUserId">
          <el-select
            v-model="form.warehouseUserId"
            placeholder="请选择仓库管理员"
            style="width: 100%"
          >
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  selWarehouseListApi,
  addWarehouseApi,
  updateWarehouseByIdApi,
  delWarehouseByIdApi,
  selStaffListApi
} from '@/api/system'

export default {
  name: 'WarehouseManagement',
  data() {
    return {
      listLoading: false,
      list: [
        {
          id: 1,
          code: '100',
          name: '金悦项目仓库',
          manager: '',
          enabled: true
        },
        {
          id: 2,
          code: '101',
          name: '金蝶项目仓库',
          manager: '',
          enabled: true
        },
        {
          id: 3,
          code: 'CK001',
          name: '默认仓库',
          manager: '1号仓库管理',
          enabled: true
        },
        {
          id: 4,
          code: 'CK002',
          name: '冷藏库',
          manager: '',
          enabled: true
        },
        {
          id: 5,
          code: 'CK003',
          name: '食品库',
          manager: '',
          enabled: true
        }
      ],
      // 仓库列表查询
      listQuery: {
        page: 1,
        pageSize: 10,
        name: ''
      },

      // 查询参数
      stafflistQuery: {
        page: 1,
        pageSize: 10,
        name: '',
        mobile: '',
        parent: ''
      },

      warehouseList: [], // 仓库列表
      total: 0,
      multipleSelection: [],
      dialogFormVisible: false,
      form: {
        id: undefined,
        name: '', // 仓库名称
        warehouseUserId: '' // 仓库管理员ID
      },
      rules: {
        name: [{ required: true, message: '请输入仓库名称', trigger: 'blur' }],
        warehouseUserId: [
          { required: true, message: '请选择仓库管理员', trigger: 'change' }
        ]
      },
      userList: [] // 用户列表，用于选择仓库管理员
    }
  },
  created() {
    this.getWarehouseList() // 获取仓库列表
    this.getStaffList() // 获取员工列表
  },
  methods: {
    // 获取员工列表
    async getStaffList() {
      try {
        const res = await selStaffListApi(this.stafflistQuery)
        this.userList = res.records || []
        console.log(this.userList)
      } catch (error) {
        console.error('获取员工列表失败:', error)
        this.$message.error('获取员工列表失败')
      }
    },
    // 获取仓库列表
    async getWarehouseList() {
      this.listLoading = true
      try {
        const res = await selWarehouseListApi(this.listQuery)
        this.warehouseList = res.records || []
        this.total = res.total || 0
      } catch (error) {
        console.error('获取仓库列表失败:', error)
        this.$message.error('获取仓库列表失败')
      } finally {
        this.listLoading = false
      }
    },

    // 获取用户列表
    async getUserList() {
      try {
        const res = await getUserListApi()
      } catch (error) {
        console.error('获取用户列表失败:', error)
      }
    },

    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    handleStatusChange(row) {
      this.$message({
        message: `${row.name} 状态已${row.enabled ? '启用' : '禁用'}`,
        type: 'success'
      })
    },
    handleAdd() {
      this.dialogFormVisible = true
      this.form = {
        id: undefined,
        name: '',
        no: '',
        warehouseUserId: ''
      }
      this.$nextTick(() => {
        this.$refs.warehouseForm && this.$refs.warehouseForm.clearValidate()
      })
    },
    handleEdit(row) {
      this.dialogFormVisible = true
      this.form = {
        id: row.id,
        name: row.name,
        no: row.no,
        warehouseUserId: row.warehouseUserId
      }
      this.$nextTick(() => {
        this.$refs.warehouseForm && this.$refs.warehouseForm.clearValidate()
      })
    },
    // 删除仓库
    handleDelete(row) {
      this.$confirm('此操作将永久删除该仓库, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          try {
            const res = await delWarehouseByIdApi(row.id)
            if (res.code === 1) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this.getWarehouseList()
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              })
            }
          } catch (error) {
            console.error('删除失败:', error)
            this.$message({
              type: 'error',
              message: '删除失败: ' + (error.message || '未知错误')
            })
          }
        })
        .catch(() => {
          // this.$message({
          //   type: "info",
          //   message: "已取消删除",
          // });
        })
    },
    handleImport() {
      this.$message({
        message: '导入仓库',
        type: 'info'
      })
    },
    handleExport() {
      this.$message({
        message: '导出仓库',
        type: 'info'
      })
    },
    handleRefresh() {
      this.getList()
      this.$message({
        message: '刷新成功',
        type: 'success'
      })
    },
    // 新增/编辑仓库
    submitForm() {
      this.$refs.warehouseForm.validate(async(valid) => {
        if (valid) {
          try {
            const params = {
              name: this.form.name,
              no: this.form.no,
              warehouseUserId: this.form.warehouseUserId
            }

            if (!this.form.id) {
              // 新增仓库
              const res = await addWarehouseApi(params)
              if (res.code === 1) {
                this.$message({
                  type: 'success',
                  message: '新增成功!'
                })
              } else {
                this.$message({
                  type: 'error',
                  message: res.msg
                })
              }
            } else {
              // 编辑仓库
              const res = await updateWarehouseByIdApi({
                ...params,
                id: this.form.id
              })
              if (res.code === 1) {
                this.$message({
                  type: 'success',
                  message: '编辑成功!'
                })
              } else {
                this.$message({
                  type: 'error',
                  message: res.msg
                })
              }
            }

            this.dialogFormVisible = false
            this.getWarehouseList() // 刷新列表数据
          } catch (error) {
            console.error('操作失败:', error)
            this.$message({
              type: 'error',
              message: '操作失败: ' + (error.message || '未知错误')
            })
          }
        }
      })
    },
    // 查询
    handleFilter() {
      this.listQuery.page = 1
      this.getWarehouseList()
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.top-navbar {
  margin-bottom: 20px;
}

.left-nav {
  display: flex;
  align-items: center;
}

.left-nav .title {
  font-size: 18px;
  font-weight: bold;
  margin-right: 15px;
}

.right-nav {
  text-align: right;
}

.pagination-container {
  text-align: center;
  margin-top: 20px;
}

.dialog-footer {
  text-align: center;
}
</style>
